import { Flex, List, Space, Tag } from 'antd';
import { ExternalLink } from './ExternalLink';
import { LibResult } from './Lib.interfaces';
import { LibResultField } from './LibResultField';
import { useLibStore } from './useLibStore';

interface LibListItemProps {
  item: LibResult;
}

export function LibListItem({ item: result }: LibListItemProps) {
  const { setQuery } = useLibStore();
  const { item } = result;
  const title = (
    <Flex>
      <Space style={{ flex: 1 }}>
        <LibResultField value={item.name} result={result} matchKey='name' />
      </Space>
      <Space align='end'>
        {item.links?.git ? (
          <ExternalLink href={item.links.git}>GIT</ExternalLink>
        ) : null}
        {item.links?.home ? (
          <ExternalLink href={item.links.home}>HOME</ExternalLink>
        ) : null}
        {item.links?.registry ? (
          <ExternalLink href={item.links.registry}>REGISTRY</ExternalLink>
        ) : null}
      </Space>
    </Flex>
  );
  const desc = (
    <div>
      <div className='lib-desc'>
        <LibResultField
          value={item.desc || ''}
          result={result}
          matchKey='desc'
        />
      </div>
      <div className='lib-tag-list'>
        {item.tags?.map((tag, index) => (
          <Tag
            className='lib-tag'
            onClick={() => setQuery('tag:' + tag)}
            key={tag}
          >
            <LibResultField
              value={tag}
              result={result}
              matchKey='tags'
              refIndex={index}
            />
          </Tag>
        ))}
      </div>
    </div>
  );
  return (
    <List.Item>
      <List.Item.Meta title={title} description={desc} />
    </List.Item>
  );
}
